﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebSocketDemo.Models;

namespace WebSocketDemo.Manager
{
    /// <summary>
    /// 管理聊天记录缓存
    /// </summary>
    public class MsgHistoryManager
    {

        /// <summary>
        /// 单例
        /// </summary>
        public static MsgHistoryManager Singleton { get; } = new MsgHistoryManager();

        /// <summary>
        /// 缓存集合
        /// </summary>
        private ConcurrentDictionary<string, List<MsgTemplate>> dict = null;

        /// <summary>
        /// 构造函数实例化缓存键值对
        /// </summary>
        private MsgHistoryManager()
        {
            dict = new ConcurrentDictionary<string, List<MsgTemplate>>();
        }

        /// <summary>
        /// 新增缓存
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        public void AddMsg(string id, MsgTemplate model)
        {
            dict.TryGetValue(id, out List<MsgTemplate> list);
            if (list == null)
            {
                list = new List<MsgTemplate>();
            }
            list.Add(model);
            dict.AddOrUpdate(id, list, (a, b) => list);
        }

        public List<MsgTemplate> GetMsgList(string id)
        {
            dict.TryGetValue(id, out List<MsgTemplate> list);
            if (list == null)
            {
                list = new List<MsgTemplate>();
            }
            return list;
        }
    }
}
